//
//  JSMLeavingViewController.m
//  TakeYouTourTogether
//
//  Created by king on 15/11/26.
//  Copyright © 2015年 king. All rights reserved.
//

#import "JSMLeavingViewController.h"
#import "JSMLeavingFooterCollectionViewCell.h"
#import "JSMLeavingFooterCollectionReusableView.h"
#import "JSMLeavingHeaderScollViewWebController.h" // 轮播图详情
#import "JSMLeavingHeaderCollectionDetailsViewController.h" //头部collectionView详情页面
#import "JSMLeavingFooterCollectionViewController.h" // 底部collectionView点击进去的详情
#import "JSMLeavingMoreViewController.h" // 更多
@interface JSMLeavingViewController ()<UITableViewDataSource, UITableViewDelegate, JSMLeavingWithCollectionTableViewCellDelegate, JSMScrollViewPackage, UICollectionViewDataSource, UICollectionViewDelegate>
@property(nonatomic, strong)BaseTableView *leavingTableView;
@property(nonatomic, strong)NSMutableArray *headerScrollArr;
@property(nonatomic, strong)NSMutableArray *showCityArr;
@property(nonatomic, strong)NSMutableArray *leavingListArr;
@property(nonatomic, strong)NSMutableArray *hotArr;
@property(nonatomic, strong)NSMutableArray *mainArr;
@property(nonatomic, strong)NSMutableArray *moreArr;
@property(nonatomic, strong)BaseCollectionView *headerCollectionView;
@property(nonatomic, strong)BaseCollectionView *footerCollectionView;
@property(nonatomic, strong)BaseView *headerView;
@end

@implementation JSMLeavingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"启程";
    self.navigationController.navigationBar.translucent = NO;

    self.leavingTableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    [self.leavingTableView.header beginRefreshing];
    [self createFooter];
    [self createHeaderView];
    
}

- (void)readCache {
    
    self.headerScrollArr = [ReadCacheTool getModelInPlist:@"LeavingHeaderScroll.plist"];
    self.showCityArr = [ReadCacheTool getModelInPlist:@"LeavingShowCity.plist"];
    self.leavingListArr = [ReadCacheTool getModelInPlist:@"LeavingList.plist"];
    self.moreArr = [ReadCacheTool getModelInPlist:@"LeavingMore.plist"];
    self.hotArr = [ReadCacheTool getModelInPlist:@"LeavingHot.plist"];
    self.mainArr = [ReadCacheTool getModelInPlist:@"LeavingMain.plist"];
    if (self.headerScrollArr.count > 0) {
        
        [self createHeaderScrollView];
    }
    [self.leavingTableView reloadData];
    [self.footerCollectionView reloadData];
    [self.headerCollectionView reloadData];


}
#pragma mark -footerCollectionView
- (void)createFooter {
    UICollectionViewFlowLayout *footeFlowLayout = [[UICollectionViewFlowLayout alloc] init];
    footeFlowLayout.itemSize = CGSizeMake((VIEWWIDTH - 30) / 5, 30);
    self.footerCollectionView = [[BaseCollectionView alloc] initWithFrame:CGRectMake(0, 0, VIEWWIDTH, 120) collectionViewLayout:footeFlowLayout];
    self.footerCollectionView.contentInset = UIEdgeInsetsMake(10, 15, 10, 15);
    self.leavingTableView.tableFooterView = self.footerCollectionView;
    
    self.footerCollectionView.dataSource = self;
    self.footerCollectionView.delegate = self;
    
    [self.footerCollectionView registerClass:[JSMLeavingFooterCollectionViewCell class] forCellWithReuseIdentifier:@"footerCollectionViewCell"];
    footeFlowLayout.headerReferenceSize = CGSizeMake(VIEWWIDTH, 30);
    [self.footerCollectionView registerClass:[JSMLeavingFooterCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"footerCollectionViewfooter"];
}

#pragma mark 刷新加载
- (void)headerRefresh {
    [self readCache];
    [self createData];

}
#pragma mark
- (void)createData {
          // 轮播图
    [AFNetworkingTool getUrl:@"http://open.qyer.com/qyer/special/topic/special_list?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v=1&track_deviceid=99000536219286&track_app_version=6.8.1&track_app_channel=xiaomi&track_device_info=armani&track_os=Android4.3&app_installtime=1445415562220&lat=38.867122&lon=121.515836&page=1&count=10" hudSuperView:self.view result:JSON success:^(id result) {
        if (result != nil) {
            self.headerScrollArr = [NSMutableArray array];
            self.headerScrollArr = [JSMLeavingScrollModel baseModelByArr:result[@"data"]];
            if (self.headerScrollArr.count > 0) {
                
                [self createHeaderScrollView];
            }

            // 缓存
            [ReadCacheTool saveModel:self.headerScrollArr toPlist:@"LeavingHeaderScroll.plist"];
        }
        [self.headerCollectionView reloadData];
        [self.leavingTableView reloadData];
        
    } failure:^(NSError *error) {
        
    }];
    // 首页头部滚动展示部分
    [AFNetworkingTool getUrl:@"http://api.breadtrip.com/destination/v3/" hudSuperView:self.view result:JSON success:^(id result) {
        if (result != nil) {
            self.showCityArr = [NSMutableArray array];
            NSMutableArray *headerShowArr = [JSMLeavingHeaderShowModel baseModelByArr:result[@"elements"]];
            self.showCityArr = [headerShowArr.lastObject dataMarr];
            // 缓存
            [ReadCacheTool saveModel:self.showCityArr toPlist:@"LeavingShowCity.plist"];
        }
        [self.headerCollectionView reloadData];
        [self.leavingTableView reloadData];
    } failure:^(NSError *error) {
        
    }];
    // 首页内容部分数据解析
    [AFNetworkingTool getUrl:@"http://api.breadtrip.com/v2/index/?lat=38.88266396464282&lng=121.5394998985486&sign=0a6f115710b159cf662cbb8faf26a7c6" hudSuperView:self.view result:JSON success:^(id result) {
        if (result != nil) {
            self.leavingListArr = [NSMutableArray array];
            NSMutableArray *receiveArr = result[@"data"][@"elements"];
            // 先找到对应的数据源中的数组
            NSMutableArray *resultArr = [NSMutableArray array];
            // 由于上述数组中的第一项不是需要使用的数据，所以用一下数组遍历的方法移除上述数组中的第一项
            for (NSInteger i = 1; i < receiveArr.count; i++) {
                resultArr[i - 1] = receiveArr[i];
            }
            self.leavingListArr = [JSMLeavingListModel baseModelByArr:resultArr];
            self.hotArr = [NSMutableArray array];
            self.mainArr = [NSMutableArray array];
            for (JSMLeavingListModel *model in self.leavingListArr) {
                if (model.type == TypeListHot) {
                    [self.hotArr addObject:model];
                } else if (model.type == TypeListContent) {
                    [self.mainArr addObject:model];
                }
            }
            [ReadCacheTool saveModel:self.hotArr toPlist:@"LeavingHot.plist"];
            [ReadCacheTool saveModel:self.mainArr toPlist:@"LeavingMain.plist"];
         
        }
        [self.leavingTableView reloadData];
    } failure:^(NSError *error) {
        
    }];
    
    // 专题部分数据
    [AFNetworkingTool getUrl:@"http://tubu.ibuzhai.com/rest/v2/trail/regions?&api_version=1&app_version=4.3.2&device_type=2" hudSuperView:self.view result:JSON success:^(id result) {
        if (result != nil) {
            self.moreArr = [NSMutableArray array];
            self.moreArr = [JSMLeavingMoreModel baseModelByArr:result[@"regions"]];
            // 缓存
            [ReadCacheTool saveModel:self.moreArr toPlist:@"LeavingMore.plist"];
        }
        [self.leavingTableView reloadData];
        [self.footerCollectionView reloadData];
        [self.headerCollectionView reloadData];
    } failure:^(NSError *error) {
        
    }];

    [self.leavingTableView.header endRefreshing];
}

- (UITableView *)leavingTableView {
    if (!_leavingTableView) {
        _leavingTableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, VIEWWIDTH, VIEWHEIGHT - 64) style:UITableViewStyleGrouped];
        _leavingTableView.dataSource = self;
        _leavingTableView.delegate = self;
        _leavingTableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 15);
        [self.view addSubview:_leavingTableView];
    }
    return _leavingTableView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }else {
        return self.hotArr.count;
    }
}
// heightForHeaderInSection
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return VIEWWIDTH * 2 / 5;
    } else {
        return 200;
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    BaseView *headerSectionView = [[BaseView alloc] initWithFrame:CGRectMake(0, 0, VIEWWIDTH, 30)];
    BaseLabel *titleLabel = [[BaseLabel alloc] initWithFrame:CGRectMake(15, 0, (VIEWWIDTH - 30) / 3, 30)];
    [headerSectionView addSubview:titleLabel];
    if (section == 0) {
        titleLabel.text = @"精品分享";
        titleLabel.textColor = [UIColor orangeColor];
        BaseButton *clickMoreButton = [BaseButton buttonWithType:UIButtonTypeCustom];
        clickMoreButton.frame = CGRectMake(VIEWWIDTH * 2 / 3, 0, VIEWWIDTH / 3, 30);
        [headerSectionView addSubview:clickMoreButton];
        [clickMoreButton setTitle:@"更多>>" forState:UIControlStateNormal];
        clickMoreButton.titleLabel.textAlignment = NSTextAlignmentRight;
        [clickMoreButton setTitleColor:[UIColor colorWithRed:0.285 green:0.704 blue:1.000 alpha:1.000] forState:UIControlStateNormal];
        [clickMoreButton addTarget:self action:@selector(clickMoreButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    } else if (section == 1) {
        titleLabel.text = @"热门推荐";
        titleLabel.textColor = [UIColor orangeColor];
    }
    return headerSectionView;
                                   
}

- (void)clickMoreButtonAction:(UIButton *)button {
    JSMLeavingMoreViewController *moreVC = [[JSMLeavingMoreViewController alloc] init];
    moreVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:moreVC animated:YES];
    }

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        static NSString *reuse = @"leavingTableView";
    JSMLeavingWithCollectionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[JSMLeavingWithCollectionTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse];
    }
    cell.mainMarr = self.mainArr;
    cell.delegate = self;
    return cell;
    } else {
        static NSString *reuse = @"leavingHotTableViewCellReuse";
        JSMLeavingHotTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[JSMLeavingHotTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse];
        }
        JSMLeavingMainAndHotModel *hotModel = [[JSMLeavingMainAndHotModel alloc] init];
        hotModel = [self.hotArr[indexPath.row] dataArr][0];
        [cell.mainImageView sd_setImageWithURL:[NSURL URLWithString:hotModel.cover_image] placeholderImage:PlaceHolderImage];
        cell.titleLabel.text = [NSString stringWithFormat:@"%@", hotModel.popular_place_str];
        return cell;
    }
}
#pragma mark tableView的cell嵌套collectionView,实现点击collectionView的cell跳转
- (void)pushToNextPage:(NSUInteger)modelId {
    JSMLeavingMainDetailsViewController *leavingMainDetail = [[JSMLeavingMainDetailsViewController alloc] init];
    leavingMainDetail.mainModel = [self.mainArr[modelId] dataArr][0];
    leavingMainDetail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:leavingMainDetail animated:YES];
}
- (void)createHeaderView {
    self.headerView = [[BaseView alloc] initWithFrame:CGRectMake(0, 0, VIEWWIDTH, 300)];
    self.leavingTableView.tableHeaderView = self.headerView;
    
    // 在tableView的tableViewheaderView上添加collectionview
    UICollectionViewFlowLayout *headerFlowLayout = [[UICollectionViewFlowLayout alloc] init];
    headerFlowLayout.itemSize = CGSizeMake((SCREENWIDTH - 40) / 3, (SCREENWIDTH - 30) / 5);
    self.headerCollectionView = [[BaseCollectionView alloc] initWithFrame:CGRectMake(0, 200, SCREENWIDTH, 100) collectionViewLayout:headerFlowLayout];
    [self.headerView addSubview:self.headerCollectionView];
    self.headerCollectionView.dataSource = self;
    self.headerCollectionView.delegate = self;
    self.headerCollectionView.contentInset = UIEdgeInsetsMake(10, 10, 10, 10);
    self.headerCollectionView.bounces = NO;
    self.headerCollectionView.showsHorizontalScrollIndicator = NO;
    headerFlowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.headerCollectionView.layer.borderColor = [[UIColor orangeColor] CGColor];
    [self.headerCollectionView registerClass:[JSMLeavingHeaderCollectionViewCell class] forCellWithReuseIdentifier:@"headerCollectionView"];

}
#pragma mark 创建轮播图
- (void)createHeaderScrollView {
    NSMutableArray *imagesArray = [NSMutableArray array];
    for (NSInteger i = 0; i < self.headerScrollArr.count; i++) {
        [imagesArray addObject:[self.headerScrollArr[i] photo]];
    }
    JSMScrollViewPackage *scroll = [[JSMScrollViewPackage alloc] initWithFrame:CGRectMake(0, 0, VIEWWIDTH, 200) imagesArray:imagesArray];
    [self.headerView addSubview:scroll];
    scroll.delegate = self;
    
    }
#pragma mark --轮播图点击方法
- (void)detailWebViewWithTag:(NSInteger)tag {
    JSMLeavingHeaderScollViewWebController *headerScrollViewWeb = [[JSMLeavingHeaderScollViewWebController alloc] init];
    headerScrollViewWeb.headerScollModel = self.headerScrollArr[tag];
    headerScrollViewWeb.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:headerScrollViewWeb animated:YES];
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (kind == UICollectionElementKindSectionHeader) {
        JSMLeavingFooterCollectionReusableView *footerReuseableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footerCollectionViewfooter" forIndexPath:indexPath];
        footerReuseableView.titleLabel.text = @"专题";
        return footerReuseableView;
    }
    return nil;
}

#pragma mark --CollectionView的方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (collectionView == self.headerCollectionView) {
        return self.showCityArr.count;
    } else {
        return self.moreArr.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    // 第二部分
    if (collectionView == self.headerCollectionView) {
        JSMLeavingHeaderCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"headerCollectionView" forIndexPath:indexPath];
        
       [cell.mainImageView sd_setImageWithURL:[NSURL URLWithString:[self.showCityArr[indexPath.row] cover_route_map_cover]] placeholderImage:PlaceHolderImage];
      return cell;
    } else if (collectionView == self.footerCollectionView) {
        // 专题 第四部分
        JSMLeavingFooterCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"footerCollectionViewCell" forIndexPath:indexPath];
        cell.mainLabel.text = [self.moreArr[indexPath.row] regionStr];
       
        return cell;
    }
    return nil;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.headerCollectionView) {
        JSMLeavingHeaderCollectionDetailsViewController *headerCollectionDetails = [[JSMLeavingHeaderCollectionDetailsViewController alloc] init];
        headerCollectionDetails.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:headerCollectionDetails animated:YES];
        headerCollectionDetails.showCityModel = self.showCityArr[indexPath.row];
    } else if (collectionView == self.footerCollectionView) {
        JSMLeavingFooterCollectionViewController *footerMoreProvince = [[JSMLeavingFooterCollectionViewController alloc] init];
        footerMoreProvince.hidesBottomBarWhenPushed = YES;
        footerMoreProvince.moreArr = self.moreArr;
        [self.navigationController pushViewController:footerMoreProvince animated:YES];
        
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    JSMLeavingHotDetailsViewController *hotDetails = [[JSMLeavingHotDetailsViewController alloc] init];
    hotDetails.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:hotDetails animated:YES];
    hotDetails.leavingHotModel = [self.hotArr[indexPath.row] dataArr][0];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
